// ==UserScript==
// @name        MouseHunt Marketplace Auto
// @namespace   
// @description Perform transaction automatically.
// @include     http://www.mousehuntgame.com/trade.php
// @include     http://www.mousehuntgame.com/trade.php#
// @include		http://www.mousehuntgame.com/canvas/trade.php
// @include		http://www.mousehuntgame.com/canvas/trade.php?*
// @include		http://www.mousehuntgame.com/trade.php?*
// @exclude		http://mousehuntgame.com/trade.php
// @exclude		http://www.mousehuntgame.com/
// ==/UserScript==

// parameters!



// config
var alert_user = true;		// pop up upon king reward
var reload_enabled = true;  // option enabling page reload
var reload_alert = false;	// alert when reloading
var reload_second = 3600;	// time interval to check if items sold
var reload_timeout = 1200;	// time interval to reload upon encountering page load timeout
var trade_search = 1;		// first # number of trades to look at
var trade_refresh = 0.5; 	// time interval to refresh trade list, in seconds
var count_limit = 60;
var count_rate = 100;

// trade refresh link
var refresh_link = "http://www.mousehuntgame.com/canvas/trade.php?hgref=hud";

// list of items on marketplace
// Class 1: Bait
var sb = "super_brie_cheese";
var maki = "maki_cheese";
var moon = "moon_cheese";

// Class 2: Charm
var anchor;
var s_rotten = "super_staling_trinket";
var antiskele;
var dragonbane;
var cavalry = "flame_march_cavalry_trinket";
var mage = "flame_march_mage_trinket";
var scientist;
var prospector;
var rotten = "staling_trinket";
var s_cavalry = "super_flame_march_cavalry_trinket";
var s_mage = "super_flame_march_mage_trinket";

// Class 3: Collectible
var sock = "zugzwang_sock_collectible";

// Class 4: Crafting Item
var tiki_bp = "tiki_base_blueprints_crafting_item";
var flameshard = "flameshard_crafting_item";
var flawed_orb = "flawed_orb_crafting_item";
var simple_orb = "simple_orb_crafting_item";
var flawless_orb = "flawless_orb_crafting_item";
var divine_orb = "perfect_orb";
var oasis_bead;
var horseshoe = "desert_horseshoe_crafting_item";
var mage_cloth = "heatproof_mage_cloth_crafting_item";
var sandblasted_metal;
var sphynx_crystal;
var clock_skin = "clock_winter_past_skin";
var fluffy_skin = "fluffy_deathbot_skin_crafting_item";
var grungy_skin = "grungy_deathbot_skin_crafting_item";
var ice_skin = "icy_rhinobo_skin_crafting_item";
var ninja_skin = "ninja_ambush_skin_crafting_item";

// Class 5: Skin
// Class 6: Special

// Removed from marketplace
var basket = "wishing_well_basket_convertible";

// SELL
var sell_item = maki;		// item to be sold (see list of items)
var sell_quantity = 1; 		// minimum quantity of maki to be sold
var sell_price = 14999;		// minimum price of maki to be sold

// BUY
var buy_itemClass = 1;		// item class number
var buy_itemType = 0;		// item type number
var buy_max_quantity = 0;	// maximum quantity to buy, set 0 to buy any amount
var buy_max_price = 10400;	// maximum price to pay
var buy_rush_price = 9000;	// price to buy ignoring gold_reserve
var gold_reserve = 10000000;// amount of gold to keep

// not implemented
var ai_auto = false;		// allow ai to judge if the transaction is worthy
var profit_margin = 10;		// acceptable minimum profit (after tax), in percentage


var filterButton;			// "Go Button" on buy page

// search for elements defined by 'query'
function xpath(query) 
{
	return document.evaluate(query, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
}


// click respective link or button
function click(element)
{
	event = 'click';
	if (document.createEventObject)
	{
		// dispatch for IE
		var evt = document.createEventObject();
		return element.fireEvent('on' + event, evt)
	}
	else
	{
		// dispatch for firefox + others
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent(event, true, true ); // event type,bubbling,cancelable
		return !element.dispatchEvent(evt);
	}
}


// read the string representation of number (5,000 -> 5000)
function parseNumber(string)
{
	string = string.replace(/,/g, "");
	return parseInt(string);
}


// refresh the marketplace
function reloadPage()
{
	if(reload_enabled)
	{
		GM_log("reloading in " + reload_timeout + " seconds!");
		if(reload_alert) { alert("reloading in " + reload_timeout + " seconds!"); }
		window.setTimeout(function() 
		{ 
			window.location.href = refresh_link
		}, reload_timeout * 1000);
	}
}


// receive gold after successful sale
function claim(count)
{
	var jsDialogClose = document.getElementById('jsDialogClose');
	
	// wait for pop up to appear
	if(!jsDialogClose)
	{
		if(count < count_limit) { window.setTimeout(function() { claim(count+1) }, count_rate); }
		else { reloadPage(); }
		return;
	} 
	else
	{
//		var popup = jsDialogClose.parentNode.childNodes[2].childNodes[0]; // textContent = you got gold
		var sellText = jsDialogClose.parentNode.childNodes[3].textContent;
		GM_log(sellText);
		reloadPage();
	}
}


// purchase under-priced items
function buy(count)
{ 
	if(count == 0)
	{
		var itemTradeList = document.getElementById('acd-items');
		var itemClassButton = itemTradeList.childNodes[2*buy_itemClass-2];
		var itemTypeButton = itemTradeList.childNodes[2*buy_itemClass-1].childNodes[0].childNodes[buy_itemType];
		filterButton = document.getElementById('filter_button');
		click(itemClassButton);
		click(itemTypeButton);
		click(filterButton);
		count++;
	}

	var tradeList1 = document.getElementById('tradeList1');
	// refresh if shopping list doesn't show
	if(!tradeList1.childNodes[0])
	{
		if(count < count_limit) { window.setTimeout(function() { buy(count+1) }, count_rate); }
		else { reloadPage(); }
		return;
	}

	var tbody = tradeList1.childNodes[0].childNodes[1];
	for(var i=0; i < Math.min(tbody.childElementCount, trade_search); i++)
	{
		var ithTrade = tbody.childNodes[i];
		var quantity = parseNumber(ithTrade.childNodes[0].textContent);
		var unitCost = parseNumber(ithTrade.childNodes[1].textContent);
		var totalCost = parseNumber(ithTrade.childNodes[2].textContent);
		var purchaseLink = ithTrade.childNodes[3].childNodes[0].childNodes[0];
		var confirmPurchaseLink = ithTrade.childNodes[3].childNodes[0].childNodes[2];
		var currentGold = parseNumber(document.getElementById('hud_gold').textContent);
		
		
		// shorthand for buying condition (boolean)
		var normal_buy_rule = (unitCost <= buy_max_price) && 
							(buy_max_quantity? (quantity <= buy_max_quantity): true) && 
							(totalCost <= Math.max(currentGold - gold_reserve, 0));
		
		var rush_buy_rule = (unitCost <= buy_rush_price) &&
							(totalCost <= currentGold);
	
	
		if(normal_buy_rule || rush_buy_rule)
		{
			click(purchaseLink);
			click(confirmPurchaseLink);
			GM_log("Purchase attempt! quantity: " + quantity + ", price: " + unitCost);
		}
	}
	
//	sb_amount = document.getElementById("hgbar_currency_qty").textContent;
//	alert(sb_amount);
	window.setTimeout(function() { click(filterButton); buy(1); }, trade_refresh * 1000);
}


// run marketplace auto
function run() 
{
//	var buytab = xpath('//a[@onclick="app.views.TabBarView.page.show(0); return false;"]').snapshotItem(0);
	var tabbar = document.getElementById('tabbarControls_page');
		
	// check if marketplace is loaded correctly
	if(!(tabbar.childNodes[0]).childNodes[1])
	{
		// check king reward
		var puzzleContainer = document.getElementById('puzzleContainer');
		if(puzzleContainer)
		{
			var kingRewardText = (puzzleContainer.childNodes[1].childNodes[0].textContent).substr(0,18) ; //"Claim Your Reward!"
			if(kingRewardText == "Claim Your Reward!")
			{
				// king reward present
				GM_log("Please claim your King Reward before continue.");
				if(alert_user) { alert("Please claim your King Reward before continue."); }
				return;
			}
		}
		
		// page not loaded properly
		GM_log("Failed to load marketplace! Reload...");
		reloadPage();
		return;
	}
	
	var buytab = document.getElementById('tabbarControls_page').childNodes[0].childNodes[1].childNodes[0].childNodes[0];
	var selltab = document.getElementById('tabbarControls_page').childNodes[0].childNodes[3].childNodes[0].childNodes[0];
	var link = document.getElementById('itemTradeSlots').childNodes[0].childNodes[0].childNodes[6];

	click(selltab);
	
	if(link != null)
	{
		if(link.text == "Claim Reward")
		{
			window.location.href = link;
			return;
		} 
	}
	else
	{
		var dropSelector = document.getElementById('image_drop_down_0|selectedOption');
		var itemSelector = document.getElementById('image_drop_down_0|' + sell_item);

		// proceed to buy if no more item to sell 
		if(link != null) 
		{
			click(buytab);
			buy(0);
			return; 
		}

		var itemInput = document.getElementById('image_drop_down_0|container').parentNode.childNodes[1];		
		var itemTradeQuantity = document.getElementById('itemTradeQuantity');
		var itemTradePrice = document.getElementById('itemTradePrice');
		var postTrade = document.getElementById('itemTradeConfirm').childNodes[1].childNodes[0];
		var confirmTrade = document.getElementById('itemTradeFinalConfirm').childNodes[1];
	
		click(dropSelector);
		click(itemSelector);
		click(itemInput);
		itemTradeQuantity.value = sell_quantity;
		itemTradePrice.value = sell_price;
		click(postTrade);
		click(confirmTrade);
		return;
	}
	
	click(buytab);
	buy(0);
	
	// sound the horn if it appears
	var hornImage = document.getElementById('hornArea').childNodes[1].childNodes[0].childNodes[0];
	if((hornImage.clientHeight == 58) && (hornImage.clientWidth == 400))
	{
		// click(hornImage);
	}
}


// Marketplace Auto
// script is inactive when King Reward is present


// start after page load
window.addEventListener(
'load',
function() { run(); },
true);




